﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;


namespace auto_win
{
    public partial class LoginForm : System.Windows.Forms.Form
    {
        public LoginForm()
        {
            InitializeComponent();
            string text = readData();
            if (text != null)
            {
                string[] strings = text.Split(' ');
                textBox1.Text = strings[0];
                textBox2.Text = strings[1];
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string phone = textBox1.Text.Trim();
            string passwd = textBox2.Text.Trim();
            if(!phone.Equals("") && !passwd.Equals(""))
            {
                User user = API.signin(phone, passwd);
                if(user != null)
                {
                    writeData(phone, passwd);
                    if (user.endAt < DateTime.Now)
                    {
                        MessageBox.Show("会员已到期，请续费", "提示");
                        List<Product> prods = API.getProducts();
                        var form = new AccountForm(prods, user);
                        form.ShowDialog();
                    }
                    else
                    {
                        this.Hide();
                        var form = new MainForm();
                        form.Show();
                    }
                        
                }
            }
        }

        private string readData()
        {
            string appDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            string appSubFolder = Path.Combine(appDataFolder, "auto_chat");
            if (!Directory.Exists(appSubFolder))
            {
                Directory.CreateDirectory(appSubFolder); // 如果文件夹不存在，则创建它
            }
            string filePath = Path.Combine(appSubFolder, "accout");
            if (File.Exists(filePath))
            {
                String text = File.ReadAllText(filePath);
                return text;
            }
            return null;
        }

        private void writeData(string phone, string password)
        {
            string appDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            string appSubFolder = Path.Combine(appDataFolder, "auto_chat");
            string filePath = Path.Combine(appSubFolder, "accout");
            File.WriteAllText(filePath, phone + " " + password);
        }


        private void button2_Click(object sender, EventArgs e)
        {
            System.Environment.Exit(0);
        }

        private void form_Closed(object sender, EventArgs e)
        {
            System.Environment.Exit(0);
        }
    }
}
